package com.paris10.model;

import java.io.BufferedReader;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.annotate.JsonTypeName;

@JsonTypeName("Markdown")
public class Markdown extends AbstractSource{

	public Markdown(){}
	
	@Override
	public String getTitre() {
		// TODO Auto-generated method stub
		return this.titre;
	}

	@Override
	public void setTitre(String titre) {
		// TODO Auto-generated method stub
		this.titre=titre;
	}
	
	public Markdown(String titre, String chemin){
		this.titre=titre;
		this.chemin=chemin;
		this.date= Dates.date();
	}
	
	public AbstractSource createSource(String titre, String chemin){
		return new Markdown(titre, chemin);
	}

	@Override
	public List<Article> rechercherMotsCles(String[] motsCles){
		
		List<Article> listeArticle = new ArrayList<Article>();
		String ligne;
		List<StringBuilder> listeParagraphe = new ArrayList<StringBuilder>();
		StringBuilder paragraphe = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new FileReader(this.chemin));
			while((ligne = br.readLine()) != null){
				
				if("".equals(ligne)){
					if(paragraphe.length() != 0){
						StringBuilder paragraphecp = new StringBuilder(paragraphe.toString());
						listeParagraphe.add(paragraphecp);
						paragraphe.setLength(0);
					}
				}else{
					paragraphe.append("\n"+ligne);
				}
			}
			listeParagraphe.add(paragraphe);
			br.close();
			
			ArticleMarkdown article = new ArticleMarkdown(this.chemin);
			article.traiterData(listeParagraphe, motsCles);
			
			if(article.isInteressant()){
				File file = new File(this.chemin);
				SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
				article.setDate(sdf.format(file.lastModified()));
				article.setTitre(file.getName());
				article.setLien(file.getPath());
				listeArticle.add(article);
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
		return listeArticle;
	}
}
